import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_ywt/constant/intent_key.dart';
import 'package:flutter_ywt/third/webview/h5/h5_params.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'flutter/flutter_url_controller.dart';
import 'flutter_handle.dart';

WebViewController _controller;

///自定义的flutter_webview
class FindWebView extends StatefulWidget implements UrlController{
  Map<String, dynamic> map;
  FindWebView(this.map);

  @override
  _WebViewPageState createState() => _WebViewPageState();

  @override
  setUrl(String url) {
    print(url);
    _controller.loadUrl(url);
  }
}

class _WebViewPageState extends State<FindWebView>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  String _url;
  String _title;

  @override
  initState() {
    //坑 - 1
    super.initState();
    this._url = widget.map[INTENT_URL];
    this._title = widget.map[INTENT_TITLE];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: WebView(
          userAgent: 'YMDD',
          initialUrl: _url,
          //JS执行模式 是否允许JS执行
          javascriptMode: JavascriptMode.unrestricted,

          onWebViewCreated: (controller) {
            _controller = controller;
            //可以在初始化时，调用window方法
//            String script = "Toaster.postMessage('哈哈哈哈');";
//            String script = "window.isLogin=是否登录";
//            _controller.evaluateJavascript(script).then((result){
//              print(script + " " + result);
//            }
//            );
          },
          onPageFinished: (url) {
            _controller.evaluateJavascript("document.title").then((result) {
              setState(() {
                _title = result;
              });
            });
          },
          //拦截url
          navigationDelegate: (NavigationRequest request) {
            print("即将打开 ${request.url}");
            if (request.url.startsWith("myapp://")) {
              return NavigationDecision.prevent;
            }
            return NavigationDecision.navigate;
          },
          //和js交互的通道
          javascriptChannels: <JavascriptChannel>[
            JavascriptChannel(
                name: "callFlutter",
                onMessageReceived: (JavascriptMessage message) {
                  var content = message.message;
                  //转实体，需要toJson
                  var h5Params =
                      H5Params.fromJson(JsonDecoder().convert(content));
                  print("callFlutter： " + content);

                  callFlutter(h5Params, (str) {
                    print("callJs= " + str);
                    String script =
                        "javascript:ISJSBridge.AppCallBack('" + str + "')";
                    _controller.evaluateJavascript(script);
                  });
                })
          ].toSet(),
        ),
      ),
    );
  }
}
